import React, { useEffect, useState } from 'react'
import { Button, message, Modal, Empty, Dropdown, notification, Spin, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  cancelMerge,
  confirmSign,
  exportContract,
  exportContractDetail,
  mergeContract,
  pagePurchaseContract,
  PrintContract,
  submitContract,
  contractTodo,
  updateContractPayType,
  trackConfirmContract,
  supplyDuctConfirmContract,
} from '@/api/purchase'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { applicationTypeEnum, OperationContractActionsType, OperationLogType } from '@/constant'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import { UploadOutlined, DownOutlined } from '@ant-design/icons'
import UploadFile from '@/components/UploadFile'
import {
  CONTRACT_STATUS_OPTIONS,
  FIRST_ORDER_RETURN_ORDER_OPTIONS,
  MERGE_STATUS_OPTIONS,
  PURCHASEWAY_OPTIONS,
} from '@/constant/purchase'
import { getProductClassConfigByType, getSpuOptions } from '@/api/goods'
import dayjs from 'dayjs'
import { downloadByOwnUrl, exportNotification, getRecentSixMonths } from '@/utils/util'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useCachePage from '@/hooks/useCachePage'
import useSearchUser from '@/hooks/useSearchUser'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [isModalShow, setIsModalShow] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const [searchOptions, setOptions] = useState<IOptionItem[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [menuItemsExport, setmenuItemsExport] = useState<{ key: string; label: string }[]>([])
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'contractCode',
    OperationLogType.PURCHASE_CONTRACT,
  )
  const [CountNum, setCountNum] = useState<{
    waitSubmitNum: number
    pendingSignNum: number
    pendingWaitSupplyDuctConfirmNum: number
    pendingWaitTrackConfirmNum: number
    pendingWaitFinancialConfirmNum: number
  }>({
    waitSubmitNum: 0,
    pendingSignNum: 0,
    pendingWaitSupplyDuctConfirmNum: 0,
    pendingWaitTrackConfirmNum: 0,
    pendingWaitFinancialConfirmNum: 0,
  })
  // // 大类
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const defaultDateRange = getRecentSixMonths()
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [query] = useSearchParams()
  const contractCode = query.get('contractCode') || ''
  const customSearchType = query.get('customSearchType') || ''
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()
  const [spinning, setspinning] = useState<boolean>(false)
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(pagePurchaseContract, {
    form: form,
    defaultFieldsParams: {
      contractStatusList: contractCode ? null : [0, 1, 2, 5, 6, 7],
      createTimeStart: contractCode ? null : defaultDateRange,
      contractCodes: contractCode ? [contractCode] : null,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  useEffect(() => {
    getcontractTodo()
    const items: { key: string; label: string }[] = []
    if (buttonCodeList.includes('mergeContract')) {
      items.push({
        key: OperationContractActionsType.MERGE + '',
        label: '合并合同',
      })
    }
    if (buttonCodeList.includes('splitContract')) {
      items.push({
        key: OperationContractActionsType.CLOSE + '',
        label: '取消合并',
      })
    }
    if (buttonCodeList.includes('updateContractDate')) {
      items.push({
        key: OperationContractActionsType.UP + '',
        label: '更新合同账期',
      })
    }
    setmenuItems(items)
    const itemsExport: { key: string; label: string }[] = []
    if (buttonCodeList.includes('exportContract')) {
      itemsExport.push({
        key: '1',
        label: '导出合同总表',
      })
    }
    if (buttonCodeList.includes('exportContractDetail')) {
      itemsExport.push({
        key: '2',
        label: '导出合同明细',
      })
    }
    setmenuItemsExport(itemsExport)
    getProductClassConfig()
    if (customSearchType === '1') {
      form.resetFields()
      form.setFieldsValue({
        contractStatusList: [0],
      })
      setTimeout(() => {
        search({ contractStatusList: [0], current: 1, size: params.size, createTimeStart: null })
      }, 1)
    } else if (customSearchType === '2') {
      form.resetFields()
      form.setFieldsValue({
        contractStatusList: [6],
      })
      setTimeout(() => {
        search({ contractStatusList: [6], current: 1, size: params.size, createTimeStart: null })
      }, 1)
    } else {
      handleCacheData()
    }
  }, [])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null || contractCode) {
      const paramsData = {
        ...params,
        contractStatusList: contractCode ? null : [0, 1, 2, 5, 6, 7],
        createTimeStart: contractCode ? null : dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        createTimeEnd: contractCode ? null : dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        contractCode,
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      form.setFieldsValue({
        ...cacheData,
        createTimeStart:
          cacheData.createTimeStart && cacheData.createTimeEnd
            ? [dayjs(cacheData.createTimeStart), dayjs(cacheData.createTimeEnd)]
            : null,
        trackConfirmStartTime:
          cacheData.trackConfirmStartTime && cacheData.requiredArrivalTimeEnd
            ? [cacheData.trackConfirmStartTime, cacheData.requiredArrivalTimeEnd]
            : null,
        supplyDuctConfirmStartTime:
          cacheData.supplyDuctConfirmStartTime && cacheData.supplyDuctConfirmEndTime
            ? [cacheData.supplyDuctConfirmStartTime, cacheData.supplyDuctConfirmEndTime]
            : null,
        financialConfirmStartTime:
          cacheData.financialConfirmStartTime && cacheData.financialConfirmEndTime
            ? [cacheData.financialConfirmStartTime, cacheData.financialConfirmEndTime]
            : null,
        tinyClassIds: cacheData.tinyClassId,
        contractStatusList: cacheData?.contractStatusList != null ? cacheData.contractStatusList : null,
        contractCodes: cacheData?.contractCodes != null ? cacheData.contractCodes : null,
        purchaseOrderCodes: cacheData?.purchaseOrderCodes != null ? cacheData.purchaseOrderCodes : null,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setOptions(cacheData?.searchOptions || [])
      setUserOptions(cacheData?.UserOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      delete cacheData.SupplierOption
      delete cacheData.searchOptions
      delete cacheData.UserOptions
      delete cacheData.SpuOptions
      search({
        ...cacheData,
        createTimeStart: cacheData.createTimeStart ? cacheData.createTimeStart : null,
        createTimeEnd: cacheData.createTimeEnd ? cacheData.createTimeEnd : null,
        createBy: isRoot ? (cacheData.createBy ? cacheData.createBy : null) : null,
        trackOrderPerson: isRoot ? (cacheData.trackOrderPerson ? cacheData.trackOrderPerson : null) : null,
        contractStatusList: cacheData?.contractStatusList != null ? cacheData.contractStatusList : null,
        contractCodes: cacheData?.contractCodes != null ? cacheData.contractCodes : null,
        purchaseOrderCodes: cacheData?.purchaseOrderCodes != null ? cacheData.purchaseOrderCodes : null,
      })
    }
  }
  const getcontractTodo = async () => {
    const res = await contractTodo<{
      waitSubmitNum: number
      pendingSignNum: number
      pendingWaitSupplyDuctConfirmNum: number
      pendingWaitTrackConfirmNum: number
      pendingWaitFinancialConfirmNum: number
    }>({})
    if (res.code == 200) {
      setCountNum(res?.data)
    } else {
      setCountNum({
        waitSubmitNum: 0,
        pendingSignNum: 0,
        pendingWaitSupplyDuctConfirmNum: 0,
        pendingWaitTrackConfirmNum: 0,
        pendingWaitFinancialConfirmNum: 0,
      })
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
  }
  const onShowStyleModal = (info: ITableData) => {
    setIsModalShow(true)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onViewLogs = async (info: ITableData) => {
    viewLogs(info)
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(info)
  }
  const handleClickMore = async (info: any) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    if (info.key == OperationContractActionsType.MERGE) {
      const res = await mergeContract({ contractIds: selectedRowKeys })
      if (res.code === 200) {
        message.success('操作成功')
        setselectedRowKeys([])
        setselectedRowInfos([])
        reloadPage()
      }
    } else if (info.key == OperationContractActionsType.CLOSE) {
      const res = await cancelMerge({ contractIds: selectedRowKeys })
      if (res.code === 200) {
        message.success('操作成功')
        setselectedRowKeys([])
        setselectedRowInfos([])
        reloadPage()
      }
    } else if (info.key == OperationContractActionsType.UP) {
      const res = await updateContractPayType({ contractIds: selectedRowKeys })
      if (res.code === 200) {
        message.success('操作成功')
        setselectedRowKeys([])
        setselectedRowInfos([])
        reloadPage()
      }
      if (res?.code === 820000 && res?.failInfo) {
        const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
          return <div key={item}>{item}</div>
        })
        notification.open({
          type: 'warning',
          message: res?.msg,
          description: failInfo,
        })
      }
    }
  }
  const reloadPage = () => {
    search(params)
    getcontractTodo()
  }
  const handleClickMoreExport = async (info: any) => {
    const paramsData: Record<string, any> = {}
    if (selectedRowKeys.length > 0) {
      paramsData.contractIds = selectedRowKeys
    } else {
      Object.assign(paramsData, params)
    }
    setexportLoading(true)
    setspinning(true)
    let res: any
    if (info.key === '1') {
      res = await exportContract(paramsData)
        .catch(() => setspinning(false))
        .finally(() => {
          setexportLoading(false)
          setselectedRowKeys([])
          setselectedRowInfos([])
        })
    }
    if (info.key === '2') {
      res = await exportContractDetail(paramsData)
        .catch(() => setspinning(false))
        .finally(() => {
          setexportLoading(false)
          setselectedRowKeys([])
          setselectedRowInfos([])
        })
    }
    if (res?.code === 200 && res?.data) {
      await exportNotification(res?.data, navigate).finally(() => setspinning(false))
    }
  }
  return (
    <PageContainer className="purchase_contract_page">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">待提交</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    contractStatusList: [0],
                  })
                  search({ ...form.getFieldsValue(), createTimeStart: null, createTimeEnd: null, current: 1, size: 10 })
                  setselectedRowKeys([])
                  setselectedRowInfos([])
                }}
              >
                {CountNum.waitSubmitNum || 0}单
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">待签署</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    contractStatusList: [1],
                  })
                  search({ ...form.getFieldsValue(), createTimeStart: null, createTimeEnd: null, current: 1, size: 10 })
                  setselectedRowKeys([])
                  setselectedRowInfos([])
                }}
              >
                {CountNum.pendingSignNum || 0}单
              </Typography.Link>
            </div>
          </div>
          {isRoot && (
            <div className="wm_item">
              <div className="wm_item_title">待跟单确认</div>
              <div className="wm_item_num">
                <Typography.Link
                  underline
                  onClick={() => {
                    form.resetFields()
                    form.setFieldsValue({
                      contractStatusList: [6],
                    })
                    search({
                      ...form.getFieldsValue(),
                      createTimeStart: null,
                      createTimeEnd: null,
                      current: 1,
                      size: 10,
                    })
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  }}
                >
                  {CountNum.pendingWaitTrackConfirmNum || 0}单
                </Typography.Link>
              </div>
            </div>
          )}
          {isRoot && (
            <div className="wm_item">
              <div className="wm_item_title">待供管确认</div>
              <div className="wm_item_num">
                <Typography.Link
                  underline
                  onClick={() => {
                    form.resetFields()
                    form.setFieldsValue({
                      contractStatusList: [7],
                    })
                    search({
                      ...form.getFieldsValue(),
                      createTimeStart: null,
                      createTimeEnd: null,
                      current: 1,
                      size: 10,
                    })
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  }}
                >
                  {CountNum.pendingWaitSupplyDuctConfirmNum || 0}单
                </Typography.Link>
              </div>
            </div>
          )}
          {isRoot && (
            <div className="wm_item">
              <div className="wm_item_title">待财务确认</div>
              <div className="wm_item_num">
                <Typography.Link
                  underline
                  onClick={() => {
                    form.resetFields()
                    form.setFieldsValue({
                      contractStatusList: [2],
                    })
                    search({
                      ...form.getFieldsValue(),
                      createTimeStart: null,
                      createTimeEnd: null,
                      current: 1,
                      size: 10,
                    })
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  }}
                >
                  {CountNum.pendingWaitFinancialConfirmNum || 0}单
                </Typography.Link>
              </div>
            </div>
          )}
        </div>
      </div>
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['trackOrderPerson'], form)}
        searchConfig={[
          {
            label: '合同编号',
            name: 'contractCodes',
            placeholder: '多个编号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          { label: '创建时间', name: 'createTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            label: '合同状态',
            name: 'contractStatusList',
            type: 'Select',
            option: CONTRACT_STATUS_OPTIONS,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          { label: '合并状态', name: 'mergeStatus', type: 'Select', option: MERGE_STATUS_OPTIONS },
          {
            label: '采购订单',
            name: 'purchaseOrderCodes',
            placeholder: '多个单号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          {
            name: 'supplierId',
            label: '供应商',
            type: 'Select',
            option: SupplierOption,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: '大类',
            name: 'firstClassConfigIds',
            type: 'Select',
            option: classBig,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          {
            label: '采购方式',
            name: 'purchaseType',
            type: 'Select',
            option: PURCHASEWAY_OPTIONS,
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          { label: '首单/返单', name: 'orderType', type: 'Select', option: FIRST_ORDER_RETURN_ORDER_OPTIONS },
          {
            label: '年份',
            name: 'year',
            type: 'FixedDatePicker',
            placeholder: '请选择年份',
            config: {
              picker: 'year',
              format: 'YYYY',
              customFormat: 'YYYY',
            },
          },
          {
            name: 'seasonCode',
            label: '订单季节',
            type: 'Select',
            option: DICTDATA.order_season,
            placeholder: '请选择订单季节',
            config: {
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          {
            label: '供应链跟单',
            name: 'trackOrderPerson',
            type: 'Select',
            option: UserOptions,
            hidden: !isRoot,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchUser,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              fieldNames: { label: 'label', value: 'workId' },
            },
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
          {
            label: '跟单确认时间',
            name: 'trackConfirmStartTime',
            type: 'FixedRangePicker',
            config: { showTime: false, customFormat: 'YYYY-MM-DD' },
          },
          {
            label: '供管确认时间',
            name: 'supplyDuctConfirmStartTime',
            type: 'FixedRangePicker',
            config: { showTime: false, customFormat: 'YYYY-MM-DD' },
          },
          {
            label: '财务确认时间',
            name: 'financialConfirmStartTime',
            type: 'FixedRangePicker',
            config: { showTime: false, customFormat: 'YYYY-MM-DD' },
          },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          const paramsData = {
            ...vals,
            createTimeStart: vals?.createTimeStart?.[0] && dayjs(vals.createTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: vals?.createTimeStart?.[1] && dayjs(vals.createTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            contractStatusList: vals?.contractStatusList?.length > 0 ? vals.contractStatusList : null,
            contractCodes: vals?.contractCodes?.length > 0 ? vals.contractCodes : null,
            purchaseOrderCodes: vals?.purchaseOrderCodes?.length > 0 ? vals.purchaseOrderCodes : null,
            year: vals.year ? vals.year : null,
            seasonCode: vals.seasonCode ? vals.seasonCode : null,
            trackConfirmStartTime:
              vals?.trackConfirmStartTime && vals?.trackConfirmStartTime.length === 2
                ? vals?.trackConfirmStartTime[0]
                : null,
            trackConfirmEndTime:
              vals?.trackConfirmStartTime && vals?.trackConfirmStartTime.length === 2
                ? vals?.trackConfirmStartTime[1]
                : null,
            supplyDuctConfirmStartTime:
              vals?.supplyDuctConfirmStartTime && vals?.supplyDuctConfirmStartTime.length === 2
                ? vals?.supplyDuctConfirmStartTime[0]
                : null,
            supplyDuctConfirmEndTime:
              vals?.supplyDuctConfirmStartTime && vals?.supplyDuctConfirmStartTime.length === 2
                ? vals?.supplyDuctConfirmStartTime[1]
                : null,
            financialConfirmStartTime:
              vals?.financialConfirmStartTime && vals?.financialConfirmStartTime.length === 2
                ? vals?.financialConfirmStartTime[0]
                : null,
            financialConfirmEndTime:
              vals?.financialConfirmStartTime && vals?.financialConfirmStartTime.length === 2
                ? vals?.financialConfirmStartTime[1]
                : null,
          }
          search({
            ...paramsData,
          })
          setCachePage({
            ...paramsData,
            SpuOptions,
            SupplierOption,
            searchOptions,
            UserOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          const paramsData = {
            ...params,
            current: 1,
            size: 10,
            contractStatusList: [0, 1, 2, 5, 6, 7],
            createTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
            contractCodes: null,
            purchaseOrderCodes: null,
            trackConfirmStartTime: null,
            trackConfirmEndTime: null,
            supplyDuctConfirmStartTime: null,
            supplyDuctConfirmEndTime: null,
            financialConfirmStartTime: null,
            financialConfirmEndTime: null,
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="printContract"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  setexportLoading(true)
                  const res = await PrintContract({
                    contractCodes: selectedRowInfos.map((item) => item.contractCode),
                    fileType: 2,
                  }).finally(() => setexportLoading(false))
                  if (res.code === 200) {
                    res.data && downloadByOwnUrl(res.data)
                    message.success('操作成功')
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reloadPage()
                  }
                }}
              >
                下载合同
              </PermissionButton>
              <PermissionButton
                permission="printContractExcel"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  setexportLoading(true)
                  const res = await PrintContract({
                    contractCodes: selectedRowInfos.map((item) => item.contractCode),
                    fileType: 1,
                  }).finally(() => setexportLoading(false))
                  if (res.code === 200) {
                    res.data && downloadByOwnUrl(res.data)
                    message.success('操作成功')
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reloadPage()
                  }
                }}
              >
                下载Excel合同
              </PermissionButton>
              <PermissionButton
                permission="submitContract"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  setexportLoading(true)
                  const res = await submitContract({ contractIds: selectedRowKeys }).finally(() =>
                    setexportLoading(false),
                  )
                  if (res.code === 200) {
                    message.success('操作成功')
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reloadPage()
                  }
                }}
              >
                提交合同
              </PermissionButton>
              <PermissionButton
                permission="contractFollowConfirm"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  setexportLoading(true)
                  const res = await trackConfirmContract({ contractIds: selectedRowKeys }).finally(() =>
                    setexportLoading(false),
                  )
                  if (res.code === 200) {
                    message.success('操作成功')
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reloadPage()
                  }
                }}
              >
                跟单确认
              </PermissionButton>
              <PermissionButton
                permission="contractSupplyConfirm"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  setexportLoading(true)
                  const res = await supplyDuctConfirmContract({ contractIds: selectedRowKeys }).finally(() =>
                    setexportLoading(false),
                  )
                  if (res.code === 200) {
                    message.success('操作成功')
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reloadPage()
                  }
                }}
              >
                供管确认
              </PermissionButton>
              <PermissionButton
                permission="comfirmContract"
                loading={exportLoading}
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  setexportLoading(true)
                  const res = await confirmSign({ contractIds: selectedRowKeys }).finally(() => setexportLoading(false))
                  if (res.code === 200) {
                    message.success('操作成功')
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reloadPage()
                  }
                }}
              >
                财务确认
              </PermissionButton>
              {isRoot && menuItems.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItems,
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </div>
            <div className="table_extra_flex">
              {menuItemsExport.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItemsExport,
                    onClick: handleClickMoreExport,
                  }}
                >
                  <Button>
                    导出
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({ params, onShowStyleModal, navigate, isRoot, onViewLogs })}
        {...tableProps}
        rowKey={(rows) => rows.id}
        isScrollY
        extraHeight={64}
      />
      <Modal title="导入文件" open={isModalShow} onCancel={onCancel}>
        <UploadFile
          templateText="批量新建商品企划模版.xls"
          templateUrl="aaaa"
          onChange={() => {
            console.log(123123)
          }}
        ></UploadFile>
      </Modal>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
